from util.Service import *
# 查询系统拥有的角色 (分页 查询角色的所有信息)
def getRoleAll(page:Page = Page(),cdn:dict = {}):
    Roles = Role.getAllRole(page,cdn)
    return Roles

# 查询系统拥有的角色 (分页 查询id 角色名)
def getRoleName(page:Page = Page()):
    Roles = Role.getAllRoleName(page)
    return Roles

# 修改角色信息（角色关键字，角色名称，启用禁用状态，角色的系统属性）
def updateRole(k:dict):
    try:
        rid = k['rId']
        k = formatParam(k,['rId', 'initBy', 'initTime', 'updateBy', 'updateTime'])
        if rid == 1 and k['status'] !='1':
            return False
        Role.updateRole(rid,k)
        return True
    except:
        return False

# 给系统添加角色
def addRole(uid:int,data:dict):
    try:
        role = {
            'status' : '1',
            'initTime': datetime.utcnow(),
            'updateTime' :datetime.utcnow(),
            'initBy':uid,
            'updateBy':uid,
            'name':data['name'],
            'key':data['key'],
            'sys':'sys',
            'indexPath':data['indexPath']
        }
        return Role.addRole(role)
    except:
        return False
    
# 删除系统角色
def delRole(rids:list[int]):
    # 在用户角色映射表中删除 rid 的映射关系
    if(1 in rids):
        return '你不能删除编号为1的角色'
    database.transaction()
    try:
        with database.atomic():
            User.delUserRoleInRid(rids)
            Role.delRoleHandleInRid(rids)
            Role.delRoleMenuInRid(rids)
            Role.delRoleMenuHandleInRid(rids)
            Role.delRoleInId(rids)
            database.commit()
    except:
        database.rollback()
        return False
    return True


# 查询角色拥有的菜单
def getMenusByRId(rid):
    mids = Role.getRoleMenusIds(rid)
    return Menu.getMenusInMIds(mids)

# 查询角色拥有的能够使用的菜单按钮 和 角色拥有的菜单上的按钮
def getMenuHandles(rid):
    tags = Role.getRoleMenuHandleAll(rid)
    mids = Role.getRoleMenusIds(rid)
    smh = Menu.getAllMenuHandleInMids(mids)
    return {
        'tags':tags,
        'smh':smh
    }
    
def getRoleMenus(rid):
    mids = Role.getRoleMenusIds(rid)
    tags = Role.getRoleMenuHandleAll(rid)
    return {'mids':mids,'tags':tags}

# 修改角色菜单权限
def updateRoleMenus(rid:int,mids:list[int],htags:list[str]):
    with database.atomic() as ts:
        canAddMids = list()
        canAddHtags = list()
        try:
            Role.delRoleMenuInRid([rid])
            Role.delRoleMenuHandleInRid([rid])
            for mid in mids:
                if Menu.hasMenu(mid):
                    canAddMids.append(mid)
            for tag in htags:
                if Menu.hasMenuHandle(tag) or rid==1:
                    canAddHtags.append(tag)
            Role.addRoleMenu(rid,canAddMids)
            Role.addRoleMenuHandle(rid,canAddHtags)
            ts.commit()
        except:
            ts.rollback()
            return False
        return True
    
# 查询角色拥有的操作权限
def getHandleById(rid):
    hids = Role.getRoleHandles(rid)
    return hids

# 更新角色接口
def updateRoleHandle(rid:int,hids:list[int]):
    canAddHids = []
    with database.transaction() as ts:
        try:
            Role.delRoleHandleInRid([rid])
            for hid in hids:
                if Menu.hasHandle(hid):
                    canAddHids.append(hid)
            Role.addRoleHandle(rid,canAddHids)
            ts.commit()
        except:
            ts.rollback()
            return False
        return True
